//
//  BYCommonWebController.swift
//  Merchants
//
//  Created by kingly09 on 2020/7/16.
//  Copyright © 2020 kingly09. All rights reserved.
//

import UIKit
import WebKit
import RxSwift


class BYCommonWebController: BCMainBaseViewController {
    
      private let canGoBackKeyPath = "canGoBack"
      private let progressKeyPath = "estimatedProgress"
    
      let disposeBag = DisposeBag()
    
      var url: String = ""
      var jumpMode : Int16 = 0
    
      private var progressView: UIProgressView!
      private var goBackBtn : Button!
      private var closeBtn : Button!
      
    private var bridge: WKWebViewJavascriptBridge!
    
    fileprivate lazy var webView: WKWebView = {
        var webView = WKWebView()
        
//        let configuration = WKWebViewConfiguration()
//        configuration.userContentController = WKUserContentController()
//        configuration.preferences.javaScriptEnabled = true
//        configuration.selectionGranularity = WKSelectionGranularity.character
//        if #available(iOS 13.0, *) {
//            configuration.defaultWebpagePreferences.preferredContentMode = .mobile
//        } else {
//
//        }
//
 
        webView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight -  HOME_INDICATOR_HEIGHT)
        
        webView.uiDelegate = self
        webView.navigationDelegate = self
        webView.allowsBackForwardNavigationGestures = true
        
     
        return webView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.loadURL()
        self.setupUI()
        self.registerJSToOC()
        

    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if self.jumpMode == 0 {
             self.isNavigationBarHidden(isHidden: false)
        }else{
             self.isNavigationBarHidden(isHidden: false)
        }
        
        self.isTabBarHidden(isHidden: false)
        
        loadTableData()
      
      }
      
      //加载数据信息
      func loadTableData() {
        
      }
      
      override func viewWillDisappear(_ animated: Bool) {
          super.viewWillDisappear(animated)
       }
    /// 显示web视图
    func loadURL() {
        view.addSubview(self.webView)
         print("sdsd")
        print(self.url)
        //self.url = "http://112.74.92.216:8078/product/upload"
        self.webView.load(URLRequest(url: URL(string: self.url)!))
    }
    
    /// 注册js
    func registerJSToOC(){
        
        self.bridge = WKWebViewJavascriptBridge(for: self.webView)
        self.bridge.setWebViewDelegate(self)
        weak var weakSelf = self
        self.bridge.registerHandler("goCallback") { (data : Any?,responseCallback : WVJBResponseCallback?) in
              weakSelf?.navigationController?.popViewController(animated: true)
            let cc = "成功调用OC的方法"
            responseCallback!(cc)
        }
    }
    
    /// 主动呼叫js  js回调
    /// - Parameter functionClassName: 调用js的方法名称
    func callJSButtonClick(functionClassName: String)  {
        self.bridge.callHandler(functionClassName, data: "这是OC调用JS方法") { (data : Any?) in
            print(data!)
        }
    }
    
    func setupUI() {
        
        progressView = UIProgressView()
        progressView.tintColor = .red
        progressView.trackTintColor = kColor_white
        progressView.progress = 0.05
        view.addSubview(progressView)

        progressView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(2)
        }

        goBackBtn = Button(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
        goBackBtn.setImage(UIImage.init(named: "nav_back"), for: UIControl.State.normal)
        goBackBtn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 10)
        goBackBtn.addTarget(self, action: #selector(goBack), for: .touchUpInside)

        closeBtn = Button()
        closeBtn.setImage(UIImageMake(name: "close"), for: .normal)
        closeBtn.addTarget(self, action: #selector(popViewController), for: .touchUpInside)
        closeBtn.sizeToFit()
        closeBtn.isHidden = true

        self.navigationItem.leftBarButtonItems = [UIBarButtonItem.init(customView: goBackBtn), UIBarButtonItem.init(customView: closeBtn)]
        
        webView.addObserver(self, forKeyPath: canGoBackKeyPath, options: .new, context: nil)
        webView.addObserver(self, forKeyPath: progressKeyPath, options: .new, context: nil)
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
           //  加载进度条
           if keyPath == progressKeyPath{
               progressView.alpha = 1.0
               progressView.setProgress(Float(self.webView.estimatedProgress), animated: true)
           if webView.estimatedProgress >= 1.0 {
                   UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseOut, animations: {
                       self.progressView.alpha = 0
                   }, completion: { (finish) in
                       self.progressView.setProgress(0.0, animated: false)
                   })
               }
           }else if keyPath == canGoBackKeyPath{
               if let newValue = change?[NSKeyValueChangeKey.newKey]{
                   let newV = newValue as! Bool
                   if newV == true{

                   }else{

                   }
               }

           }
       }

       deinit {
           webView.removeObserver(self, forKeyPath: canGoBackKeyPath, context: nil)
           webView.removeObserver(self, forKeyPath: progressKeyPath, context: nil)
       }
    

}

extension BYCommonWebController{
    
    @objc func goBack(){
        if webView.canGoBack {
            webView.goBack()
        }else{
            popViewController()
        }
    }
    
    @objc func popViewController(){
        let controllers = navigationController?.viewControllers
        if controllers?.count ?? 0 > 1 {
            let vc = controllers![controllers!.count-1]
            if vc == self {
                //push
                self.navigationController?.popViewController(animated: true)
                return
            }
        }
        dismiss(animated: true, completion: nil)
    }
    

}



extension BYCommonWebController: WKNavigationDelegate {
    
      //页面开始加载时调用
       public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
           
       }
       
       // 页面加载失败时调用
     
       public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
           
           self.progressView.isHidden = true
            print("error \(error)")
       }
       
       // 当内容开始返回时调用
       public func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!){
           
       }
       
       /// 当内容加载完毕
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
        
//        if self.webView.title?.count ?? 0 > 10 {
//            if self.title?.count == 0 {
//                self.title = "详情"
//            }
//        }else{
//            self.title = self.webView.title
//        }
        
        self.closeBtn?.isHidden = false
        

        weak var weakSelf = self
        webView.evaluateJavaScript("document.title") {( data:Any?, error:Error?) in
            
            print("document.title")
            print(data!)
            
            weakSelf!.title  = data! as? String
        }
        
        UIView.animate(withDuration: 0.5) {
            weakSelf?.progressView.isHidden = true
        }
    
        
    }
       
       /// 当内容加载失败
       func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error){
           self.progressView.isHidden = true
            print("error \(error)")
       }
    
    
    ///根据WebView对于即将跳转的HTTP请求头信息和相关信息来决定是否跳转
    @available(iOS 8.0, *)
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let url = navigationAction.request.url?.absoluteString
        print("decidePolicyFor\(String(describing: url))")
        
        decisionHandler(WKNavigationActionPolicy.allow)//实现H5页面返回
    }
    
    /// 根据WebView对于即将跳转的HTTP请求头信息和相关信息来决定是否跳转
    @available(iOS 13.0, *)
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, preferences: WKWebpagePreferences, decisionHandler: @escaping (WKNavigationActionPolicy, WKWebpagePreferences) -> Void) {
        
        let url = navigationAction.request.url?.absoluteString
               print("decidePolicyFor\(String(describing: url))")
        let WebpagePreferences = WKWebpagePreferences()
        WebpagePreferences.preferredContentMode = .mobile
        decisionHandler(WKNavigationActionPolicy.allow,WebpagePreferences)//实现H5页面返回
    }
    
    
    /// 根据客户端受到的服务器响应头以及response相关信息来决定是否可以跳转
    @available(iOS 8.0, *)
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        
        decisionHandler(WKNavigationResponsePolicy.allow)
    }
    
     @available(iOS 8.0, *)
    func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!){
        
        print("redirect")
        print(webView.url!)
    }

    
}

//MARK: - WKUIDelegate
extension BYCommonWebController: WKUIDelegate {
    
    // 创建一个新的WebView
    public func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        
        return nil
    }
    
    /**
     *  web界面中有弹出警告框时调用
     *  @param webView           实现该代理的webview
     *  @param message           警告框中的内容
     *  @param frame             主窗口
     *  @param completionHandler 警告框消失调用
     */
    public func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        
        // 在原生得到结果后，需要回调JS，是通过completionHandler回调
    }
    
    /**
     *  web界面中有弹出确认框时调用
     *  @param webView           实现该代理的webview
     *  @param message           确认框中的内容
     *  @param frame             主窗口
     *  @param completionHandler 确认框消失调用
     */
    
    public func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void){
        
        
    }
    
    /**
     *  web界面中有弹出输入框时调用
     *  @param webView           实现该代理的webview
     *  @param message           输入框中的内容
     *  @param frame             主窗口
     *  @param completionHandler 输入框消失调用
     */
    
    public func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void){
        
    }
    
}

 //MARK:-WKScriptMessageHandler  可以直接将接收到的JS脚本转为OC或Swift对象
extension BYCommonWebController: WKScriptMessageHandler {
    
       func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
               
           print("JavaScript is sending a message \(message.body) \(message.name)")
               
       }
    
}
